<script setup>
import {onMounted, ref} from 'vue';
import {Back, ChatDotRound, View} from "@element-plus/icons-vue";
import router from "@/router/index.js";
import HeartIcon from "@/component/icon/HeartIcon.vue";
import {useRoute} from "vue-router";
import http from "@/request/http.js";
import {debounce} from "chart.js/helpers";

// 搜索和筛选状态
const searchQuery = ref("");
const selectedTypes = ref(['all']);
const dateRange = ref('all');
const sortOption = ref('hot');
const currentPage = ref(1); // 当前页码，初始为1
const pageSize = ref(10); // 每页条数
const hasMore = ref(true); // 是否还有更多数据
const articles = ref([]);
const isLoading = ref(false);

// 文章类型定义
let allTypes = [];
//获取文章类型
const getCategories = async () => {
  let result = []
  const data = await http.get("/article/getCategoryList?size=100")
  for (let item of data.data.records) {
    result.push({value: item.categoryName, label: item.categoryName})
  }
  return result
}

// 获取后端数据
const generateMockData = async () => {
  let results = [];

  //获取用户所选择的类型
  let categories = selectedTypes.value
  //特判一下all
  if (categories.length === 1 && categories.includes("all")) {
    categories = []
  }

  const data = await http.post('/article/getHotList',
      {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value,
        categories: categories
      }
  );

  if (data.code === 200) {
    const {records, pages} = data.data;
    results = records
    hasMore.value = currentPage.value < pages;  // 判断是否还有下一页
  } else {
    console.log("获取文章失败")
    hasMore.value = false
  }
  currentPage.value++

  return results;
};

const performSearch = () => {
  currentPage.value = 1; // 重置到第一页
};

// 处理类型选择
const handleTypeSelectAll = () => {
  if (selectedTypes.value.includes('all')) {
    // 如果勾选了"全部"，则只保留"全部"
    selectedTypes.value = ['all'];
  } else {
    // 如果取消勾选"全部"，则清空选择
    selectedTypes.value = [];
  }
  applyFilters();
};

const handleTypeChange = () => {
  // 如果选择了其他类型，则移除"全部"
  if (selectedTypes.value.length > 1 && selectedTypes.value.includes('all')) {
    selectedTypes.value = selectedTypes.value.filter(t => t !== 'all');
  }
  // 如果没有选择任何类型，则自动勾选"全部"
  if (selectedTypes.value.length === 0) {
    selectedTypes.value = ['all'];
  }
  applyFilters();
};

// 应用筛选条件，重新查找文章数据
const applyFilters = async () => {
  currentPage.value = 1; // 重置到第一页
  articles.value = []
  // 这里有一点屎，因为重新删掉数据加载后不会触发无限回滚的递归加载，
  // 加载不出滚动条，所有手动调3次让他出现滚动条
  await filteredResults()
  await filteredResults()
};

// 重置筛选条件
const resetFilters = () => {
  selectedTypes.value = ['all'];
  dateRange.value = 'all';
  sortOption.value = 'hot';
  applyFilters()
};

// 防抖函数：延迟 500ms 执行，多次调用会重置延迟，防止搜索时调用过快
const debouncedHandle = debounce(resetFilters, 400);

// 重置所有（包括搜索词）
const resetAll = () => {
  searchQuery.value = '';
  resetFilters();
};

// 过滤结果
const filteredResults = async () => {
  isLoading.value = true
  let results = await generateMockData();

  // 日期范围过滤
  if (dateRange.value !== 'all') {
    const now = new Date();
    const cutoffDate = new Date();

    switch (dateRange.value) {
      case 'today':
        cutoffDate.setHours(0, 0, 0, 0);
        break;
      case 'week':
        cutoffDate.setDate(now.getDate() - 7);
        break;
      case 'month':
        cutoffDate.setMonth(now.getMonth() - 1);
        break;
      case 'year':
        cutoffDate.setFullYear(now.getFullYear() - 1);
        break;
    }

    results = results.filter(item => new Date(item.publishTime) >= cutoffDate);
  }

  articles.value = [...articles.value, ...results]

  // 排序
  articles.value.sort((a, b) => {
    const dateA = new Date(a.publishTime).getTime();
    const dateB = new Date(b.publishTime).getTime();
    const likeCountA = a.likeCount;
    const likeCountB = b.likeCount;
    const commentCountA = a.commentCount;
    const commentCountB = b.commentCount;
    const viewCountA = a.viewCount;
    const viewCountB = b.viewCount;

    switch (sortOption.value) {
      case 'hot':
        return 0;
      case 'time':
        return dateB - dateA;
      case 'likeCount':
        return likeCountB - likeCountA;
      case 'commentCount':
        return commentCountB - commentCountA;
      case 'viewCount':
        return viewCountB - viewCountA;
      default:
        return 0;
    }
  });
  console.log("是否还有文章：" + hasMore.value)
  isLoading.value = false
}

// 辅助函数：高亮匹配的文本
const highlightMatches = (text) => {
  if (!searchQuery.value) {
    return [{text, highlight: false}];
  }

  const query = searchQuery.value.toLowerCase();
  const parts = [];
  let currentIndex = 0;

  while (currentIndex < text.length) {
    const index = text.toLowerCase().indexOf(query, currentIndex);

    if (index === -1) {
      parts.push({text: text.slice(currentIndex), highlight: false});
      break;
    }

    // 添加匹配前的文本
    if (index > currentIndex) {
      parts.push({text: text.slice(currentIndex, index), highlight: false});
    }

    // 添加匹配的文本
    parts.push({
      text: text.slice(index, index + query.length),
      highlight: true
    });

    currentIndex = index + query.length;
  }
  return parts;
};

// 初始化
const route = useRoute()
searchQuery.value = route.query.key

onMounted(async () => {
  //获取类型列表
  allTypes = await getCategories()
});

</script>

<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white dark:bg-gray-800 shadow-sm transition-all duration-300">
      <div class="container mx-auto px-4 py-4 flex flex-col md:flex-row justify-start items-center">
        <div class="flex items-center mb-4 md:mb-0">
          <h1 class="text-2xl font-bold text-blue-600 dark:text-blue-400" @click="router.push('/')">
            <el-icon size="20">
              <Back/>
            </el-icon>
            返回主页
          </h1>
        </div>

        <!-- 搜索框 -->
        <div class="relative w-full ml-52 md:w-1/2">
          <input
              v-model="searchQuery"
              class="w-full py-2 px-4 pr-10 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
              placeholder="搜索文章..."
              type="text"
              @input='debouncedHandle'
          >
        </div>
      </div>
    </header>

    <main class="container mx-auto px-4 py-8">
      <!-- 搜索结果信息 -->
      <div class="mb-6 flex flex-col md:flex-row justify-between items-start md:items-center">
        <div>
          <h2 class="text-xl font-semibold mb-1">搜索结果 for "{{ searchQuery }}"</h2>
          <p class="text-gray-500 dark:text-gray-400">找到 {{ articles.length }} 个结果</p>
        </div>

        <!-- 排序选项 -->
        <div class="mt-4 md:mt-0 w-full md:w-auto">
          <select
              v-model="sortOption"
              class="w-full md:w-auto py-2 px-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
              @change="applyFilters"
          >
            <option value="hot">热度</option>
            <option value="time">最新发布</option>
            <option value="likeCount">点赞量</option>
            <option value="commentCount">评论量</option>
            <option value="viewCount">浏览量</option>
          </select>
        </div>
      </div>

      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 筛选侧边栏 -->
        <aside class="w-full lg:w-64 shrink-0">
          <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 sticky top-24">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
              <i class="fas fa-filter mr-2 text-blue-500"></i>筛选条件
            </h3>

            <!-- 类型筛选 -->
            <div class="mb-6">
              <h4 class="font-medium mb-3 text-gray-700 dark:text-gray-300">文章类型</h4>
              <div class="space-y-2 h-64 overflow-auto">
                <label class="flex items-center">
                  <input
                      v-model="selectedTypes"
                      class="rounded text-blue-500 focus:ring-blue-500"
                      type="checkbox"
                      value="all"
                      @change="handleTypeSelectAll"
                  >
                  <span class="ml-2">全部类型</span>
                </label>
                <template v-for="type in allTypes" :key="type.value">
                  <label class="flex items-center">
                    <input
                        v-model="selectedTypes"
                        :value="type.value"
                        class="rounded text-blue-500 focus:ring-blue-500"
                        type="checkbox"
                        @change="handleTypeChange"
                    >
                    <span class="ml-2">{{ type.label }}</span>
                  </label>
                </template>
              </div>
            </div>

            <!-- 日期范围筛选 -->
            <div class="mb-6">
              <h4 class="font-medium mb-3 text-gray-700 dark:text-gray-300">发布日期</h4>
              <select
                  v-model="dateRange"
                  class="w-full py-2 px-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                  @change="applyFilters"
              >
                <option value="all">所有时间</option>
                <option value="today">今天</option>
                <option value="week">一周内</option>
                <option value="month">一个月内</option>
                <option value="year">一年内</option>
              </select>
            </div>

            <!-- 重置筛选按钮 -->
            <button
                class="w-full py-2 px-4 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 rounded-lg transition-colors flex items-center justify-center"
                @click="debouncedHandle"
            >
              <i class="fas fa-redo-alt mr-2"></i>重置筛选
            </button>
          </div>
        </aside>

        <!-- 搜索结果列表 -->
        <div class="flex-1">
          <!-- 结果为空时显示 -->
          <div v-if="articles.length === 0"
               class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-10 text-center">
            <i class="fas fa-search fa-4x text-gray-300 dark:text-gray-600 mb-4"></i>
            <h3 class="text-xl font-medium mb-2">未找到匹配结果</h3>
            <p class="text-gray-500 dark:text-gray-400 mb-6">请尝试调整搜索条件或使用不同的关键词</p>
            <button
                class="py-2 px-6 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors"
                @click="resetAll"
            >
              清除所有筛选
            </button>
          </div>

          <!-- 结果列表 -->
          <div
              v-infinite-scroll="filteredResults"
              :infinite-scroll-delay="500"
              :infinite-scroll-disabled="!hasMore || isLoading"
              :infinite-scroll-distance="300"
              style="height: 1400px; overflow:auto; margin-bottom: 4px"
          >
            <div
                v-for="(article, index) in articles"
                :key="article.articleId"
                @click="router.push({name:'article',params:{articleId:article.articleId}})"
                class="bg-white rounded-lg mb-3 shadow-sm p-4 hover:translate-y-[-5px] transition-transform duration-300 "
            >
              <div class="flex justify-between">
                <div class="flex-1 pr-4">
                  <h3 class="font-semibold mb-2 hover:text-blue-600 transition-colors line-clamp-1">
                    <a href="#">
                      <span
                          v-for="(part, index) in highlightMatches(article.title)"
                          :key="index"
                          :style="{ 'background-color': part.highlight?'khaki': 'transparent'}"
                      >
                      {{ part.text }}
                      </span>
                    </a>
                  </h3>
                  <p class="text-gray-500 text-sm mb-3 line-clamp-2">
                    <span
                        v-for="(part, index) in highlightMatches(article.summary)"
                        :key="index"
                        :style="{ 'background-color': part.highlight?'khaki': 'transparent'}"
                    >
                      {{ part.text }}
                      </span>
                  </p>
                  <div class="flex flex-wrap items-center text-sm text-gray-500 gap-x-4 gap-y-1">
                    <div class="flex items-center">
                      <img :src="article.avatar" alt="作者头像" class="w-5 h-5 rounded-full mr-1">
                      <span
                          v-for="(part, index) in highlightMatches(article.username)"
                          :key="index"
                          :style="{ 'background-color': part.highlight?'khaki': 'transparent'}"
                      >
                      {{ part.text }}
                      </span>
                    </div>
                    <span>{{ article.publishTime }}</span>
                    <div class="flex flex-wrap gap-1 mt-1">
                        <span
                            v-for="(tag, i) in article.category"
                            :key="i"
                            class="bg-gray-100 text-gray-500 px-2 py-0.5 rounded text-xs"
                        >
                          {{ tag }}
                        </span>
                    </div>
                    <div class="flex items-center">
                      <i class="fa fa-eye mr-1"></i>
                      <HeartIcon/>
                      <span>{{ article.likeCount }}</span>
                    </div>
                    <div class="flex items-center">
                      <i class="fa fa-comment mr-1"></i>
                      <el-icon>
                        <ChatDotRound/>
                      </el-icon>
                      <span>{{ article.commentCount }}</span>
                    </div>
                    <div class="flex items-center">
                      <i class="fa fa-eye mr-1"></i>
                      <el-icon>
                        <View/>
                      </el-icon>
                      <span>{{ article.viewCount }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="!hasMore">
              <p style="text-align: center;color:#999;margin-top:20px ">已经到底啦~</p>
            </div>
          </div>

        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
/* 基础样式补充 */
.dark {
  color-scheme: dark;
}

/* 平滑滚动 */
html {
  scroll-behavior: smooth;
}

/* 自定义动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 列表项动画 */
div[class*="bg-white dark:bg-gray-800 rounded-xl"] {
  animation: fadeIn 0.3s ease-out forwards;
}
</style>
